package com.itheima10;

import java.io.*;
import java.net.Socket;

public class ServerThread implements Runnable {
    private Socket s;

    public ServerThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        try {
            // 接收数据，写入文本文件
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
//            BufferedWriter bw = new BufferedWriter(new FileWriter("/Users/oscar/Desktop/HQWork/学习资料/code/MyNet/Copy.java"));
            // 解决文件名字冲突的问题
            int count = 0;
            File file = new File("/Users/oscar/Desktop/HQWork/学习资料/code/MyNet/Copy[" + count + "].java");
            while (file.exists()) {
                count++;
                file = new File("/Users/oscar/Desktop/HQWork/学习资料/code/MyNet/Copy[" + count + "].java");
            }
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));

            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
                bw.flush();
            }

            // 给出反馈
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            bufferedWriter.write("文件上传成功");
            bufferedWriter.newLine();
            bufferedWriter.flush();

            // 释放资源
            s.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
